package com.pms.web.controller.system;

import com.alipay.api.domain.Goods;
import com.pms.system.domain.PmsCheckinInfo;
import com.pms.system.domain.PmsGuestroomItem;
import com.pms.system.mapper.PmsCheckinInfoMapper;
import com.pms.system.mapper.PmsGuestroomItemMapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/system/api")
@MapperScan("com.example.alipay.dao")
public class ApiController {

    @Resource
    private PmsGuestroomItemMapper PmsGuestroomItemMapper;

    @Resource
    private PmsCheckinInfoMapper PmsCheckinInfoMapper;

    @GetMapping("/goods")
    public List<PmsGuestroomItem> getGoods() {
        return PmsGuestroomItemMapper.selectList(null);
    }

    @GetMapping("/orders")
    public List<PmsCheckinInfo> getOrders() {
        return PmsCheckinInfoMapper.selectList(null);
    }

    @Transactional
    @PostMapping("/buy")
    public boolean buy(@RequestParam Long goodsId) {
        PmsGuestroomItem PmsGuestroomItem = PmsGuestroomItemMapper.selectById(goodsId);
        int store = PmsGuestroomItem.getStore() - 1;
        if (store < 0) {
            return false;
        }
        Date date = new Date();
        PmsCheckinInfo orders = new PmsCheckinInfo();
        orders.setRoomId(goodsId);
        orders.setCreateTime(date);
        orders.setName("购买" + PmsGuestroomItem.getName() + "订单");
        orders.setCode(new SimpleDateFormat("yyyyMMdd").format(date) + System.currentTimeMillis());
        orders.setPrice(PmsGuestroomItem.getPrice().multiply(BigDecimal.ONE));

        PmsGuestroomItem.setStore(store);
        return PmsCheckinInfoMapper.insert(orders) > 0 &&  PmsGuestroomItemMapper.updateById(PmsGuestroomItem) > 0;
    }
}
